<?php

namespace app\admin\controller;

use think\Controller;

class System extends Controller
{
    public $allid;
    public $item;
    //结算
    public function count_profit()
    {
       //echo strtotime(date('Y-m-d').'23:59');
        $Projectitem = model('Projectitem');
            $items = $Projectitem->getToDayItem();
//            halt($items);
        //获取今日所有打卡项
        if(!$items){//找不到就终止
            return;
        }
//        今天的所有打卡信息
        $this->item = $items;
//        print_r($this->item);exit;
        $signed = [];//已签到人
        $notsign = [];//未签到人
        //拆分已打卡与未打卡
        foreach ($items as $k => $i) {
            if ($i['status'] == 0) {
                $notsign[] = $i;
            } else {
                $signed[] = $i;
            }
        }
//       获取所有已打卡人的id
        $allid = [];
        foreach ($signed as $x=>$h){
            array_push($allid,$h['uid']);
        }
        $this->allid = $allid;
        //已打卡的未打卡的占比
        $total = count($items);
        $signedsum = count($signed);
        $signedper = round(($signedsum/$total)*100);
        $unsignedper = 100 - $signedper;
        $arr = [
            'signed_count' => $signedper,
            'notsign_count' => $unsignedper
        ];
        model('System')->save($arr,['id' =>1]);
        //未打卡总金额
        $nosign_count = $this->count_notsign($notsign);
        //瓜分总份数
        $split_count = $this->signed_split_count($signed);

        if($split_count==0){
            return;
        }

        //print_r($split_count);exit;
        //每份金额
        $split_money = $nosign_count/$split_count;
        //三级分销制度
        foreach ($items as $j =>$v){
            $this->UserSliceprofit($v['join_money'],$v['uid']);
        }
        //记录奖金到打卡项中
        $this->add_bonus($signed, $split_money);
        //结束未打卡项目
        $this->overProject($notsign);
        //dump($nosign_count);
    }

    //计算未打卡总金额
    private function count_notsign($notsign)
    {
        $total = 0;//总金额
        foreach ($notsign as $k => $i) {
            $total += $i['join_money'];
        }
        return $total;
    }

    //已打卡瓜分总份数计算
    private function signed_split_count($signed)
    {
        $total = 0;
        if (!empty($signed)){
            foreach ($signed as $k => $i) {
                $total += $i['uniy_count'];
            }
        }
        return $total;
    }

    //记录奖金到已打卡人打卡项，并且存入会员账户
    /*
     * $signed 已打卡项
     * $split_money 每份奖励金额
     */
    private function add_bonus($signed, $split_money)
    {
        $projectItem = model('Projectitem');
        $user=model('User');
        foreach ($signed as $k => $i) {
            $money = $i['uniy_count'] * $split_money;
//            $leftmoney = $this->UserSliceprofit($money,$i['uid'],$signed);
            if($money>0){
                $res = $projectItem->where(array('id' => $i['id']))->update(array('money' => $money,'count_status'=>1));
                $user_res=$user->where(array('id'=>$i['uid']))->setInc('add_bonus',$money);
                $user->where(array('id'=>$i['uid']))->setInc('balance',$money);
                $data = [
                    'uid' => $i['uid'],
                    'type' => 'bonus',
                    'create_time' => time(),
                    'money' => $money,
                    'content' => '奖金分成,获利:' . $money. '元',
                ];
//                存入奖金日志
                db('userprofit_logs')->insert($data);
            }
        }
    }

    /*
     * 结束未打卡项的参与活动
     *$notsign 未打卡项
     */
    private function overProject($notsign)
    {
        $project = model('Project');
        foreach ($notsign as $k => $i) {
            $res = $project->overProjectById($i['pro_id']);
        }
    }

    /**
     * 用户三级分销佣金
     */
    public function UserSliceprofit($money,$userid){
//        echo $money;die;
        $config = model("System")->sysConfig();
        $rate = $config['profit_rate'];
        $rate = json_decode($rate,true);
        $user = model('User');
        $rate1 = $rate['rate1']; $rate2 = $rate['rate2']; $rate3 = $rate['rate3'];
//        $userid= cookie('uid');
        $userinfo = $user->find($userid);
        if($userinfo){
            if($userinfo['pid']!==0){
//                判断是否打卡
                if($userinfo['fuid1']){
                    //        第一级分销
                    if($this->is_card($userid)){
                        $money1 = $money*$rate3/100;
                    }else{
                            $money1 = 0;
                    }
                }else{
                    return '顶级分类';
                }

//                halt($res2);
                $res2 = $this->userinfo($userinfo['fuid1']);
                if($userinfo['fuid2']){
                    if($this->is_card($userinfo['fuid1'])){
                        $money2 = $res2['join_money']*$rate2/100;
                    }else{
                            $money2 = 0;
                    }
                }else{
//                   当只有一级取一级费率
                    $money1 = $money*$rate1/100;
                    $data1 = [
                        'uid' => $userinfo['fuid1'],
//                        'user_id' => $userinfo['fuid2'],
                        'type' => 'commission',
                        'create_time' => time(),
                        'money' => $money1,
                        'content' => '一级分成,获利:' . $money1 . '元',
                        'level' => 1,
                    ];
                    if($money1>0){
                        db('userprofit_logs')->insert($data1);
                        db('user')->where('id',$userinfo['fuid1'])->setInc('balance',$money1);
                     }
                    return 0;
                }

                if($userinfo['fuid3']){
                    $res3 = $this->userinfo($userinfo['fuid2']);
                    if($this->is_card($userinfo['fuid2'])){
                        $money3 = $res3['join_money'] *$rate1/100;
                    }else{
                        $money3 = 0;
                    }
                    $data3 = [
                        'uid' => $userinfo['fuid3'],
//                        'user_id' => $userinfo['fuid3'],
                        'type' => 'commission',
                        'create_time' => time(),
                        'money' => $money1 + $money2 + $money3,
                        'content' => '三级分成,获利:' . ($money1 + $money2 + $money3) . '元',
                    ];
                    $addmoney1 = $money1 +$money2 +$money3;
                    db('userprofit_logs')->insert($data3);
                    db('user')->where('id',$userinfo['fuid3'])->setInc('balance',$addmoney1);

                }else{
//                    当只有两级的时候
                    $money1 = $money*$rate2/100;
                    $money2 = isset($res2['join_money'])?$res2['join_money']:0 * $rate1/100;
                    $data2 = [
                        'uid' => $userinfo['fuid2'],
//                        'user_id' => $userinfo['fuid3'],
                        'type' => 'commission',
                        'create_time' => time(),
                        'money' => $money2 + $money1,
                        'content' => '二级分成,获利:' . ($money2 + $money1) . '元',
                    ];
                    if($money1 + $money2 > 0){
                        $addmoney = $money1 +$money2;
                        db('userprofit_logs')->insert($data2);
                        db('user')->where('id',$userinfo['fuid2'])->setInc('balance',$addmoney);
                    }
                    return 0;
                }

            }/*else{
                $leftmoney = $money;
            }*/
        }else{
            return false;
        }
      return 0;
    }

//    判断当前id是否打卡
    public function is_card($id){

        if(in_array($id,$this->allid)){
            return 1;
        }else{
            return 0;
        }
    }

//    找到当前id对应的打卡数据
    public function userinfo($id){
        $arr = [];
        foreach ($this->item as $k=>$v){
            if($v['uid'] == $id){
                $arr = $v;
            }
        }
        return $arr;
    }

}